package com.pqc.tbk.web.user;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pqc.tbk.entity.ConstProp;
import com.pqc.tbk.entity.account.User;
import com.pqc.tbk.service.account.ShiroDbRealm.ShiroUser;
import com.pqc.tbk.service.account.UserService;
import com.pqc.tbk.service.mail.MailService;
import com.pqc.tbk.utils.CookiesCRUD;
import com.pqc.tbk.utils.Digest;
import com.pqc.tbk.utils.StringUtil;
import com.pqc.tbk.utils.UserUtil;

/**
 * 
 * 主要对用户详情的更新<br>
 * 用户的基本信息,用户的密码,以及邮箱支付宝以及手机的绑定
 * 
 */
@Controller
@RequestMapping("/user/home")
public class UserDetailController {

	private UserService userService;
	private MailService mailService;

	@RequestMapping("")
	public String home() {
		return "user/home";
	}

	@RequestMapping("info")
	public String info(final Model model) {
		final Long id = ((ShiroUser) SecurityUtils.getSubject().getPrincipal())
				.getId();
		model.addAttribute("user", userService.findUser(id));
		return "user/info";
	}

	@RequestMapping("safe")
	public String safe(final Model model) {
		final Long id = ((ShiroUser) SecurityUtils.getSubject().getPrincipal())
				.getId();
		model.addAttribute("user", userService.findUser(id));
		return "user/safe";
	}

	/**
	 * 修改密码
	 * 
	 * @param oPwd
	 *            旧密码
	 * @param nPwd
	 *            新密码
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "updatePwd", method = RequestMethod.POST)
	@ResponseBody
	public String updatePwd(@RequestParam("opwd") final String oPwd,
			@RequestParam("npwd") final String nPwd) {
		final Subject subject = SecurityUtils.getSubject();
		final Long id = ((ShiroUser) subject.getPrincipal()).getId();
		return (userService.updatePwd(oPwd, nPwd, id)) ? "{\"flag\": true}"
				: "{\"flag\": false}";
	}

	/**
	 * 修改用户基本信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "updateBasicInfo", method = RequestMethod.POST)
	@ResponseBody
	public String updateBasicInfo(final User user) {
		final Long id = UserUtil.getUID();
		return (userService.updateBasicInfo(user, id)) ? "{\"flag\": true}"
				: "{\"flag\": false}";
	}

	/**
	 * 邮箱验证（发送）
	 * 
	 * @param email
	 * @return
	 */
	@RequestMapping(value = "bindEmail", method = RequestMethod.POST)
	@ResponseBody
	public String bindEmail(@RequestParam("email") final String email) {
		return mailService.emailBind(email) ? "{\"flag\": true}"
				: "{\"flag\": false}";
	}

	/**
	 * 邮箱验证（验证）
	 * 
	 * @param
	 */
	@RequestMapping("emailVerify")
	public String emailVerify(final String email, final Long t,
			final String sign) {
		final int n = userService.emailVerify(email, t, sign);
		if (n == 1) {
			System.out.println("绑定成功");
		} else if (n == 2) {
			System.out.println("非法的参数");
		} else if (n == 3) {
			System.out.println("链接已失效");
		} else if (n == 4) {
			System.out.println("不能重复绑定");
		}
		return "";
	}

	@RequestMapping(value = "/bindTel", method = RequestMethod.POST)
	@ResponseBody
	public String bindTel(final String tel, final HttpServletResponse response,
			final HttpServletRequest request) {
		final String check = "^(13[0-9]{9})|(15[0-9]{9})|(18[0-9]{9})$";
		final Pattern regex = Pattern.compile(check);
		final Matcher matche = regex.matcher(tel);
		if (!matche.matches()) {
			return ConstProp.Operation.FAILURE;
		} else {
			// 判断该号码是否已经绑定
			if (userService.countByTel(tel) > 0) {
				return ConstProp.Operation.EXIST;
			}
			// 如果该缓存任然存在
			final String value = CookiesCRUD.getCookieByName(request,
					ConstProp.BindTel.COOKIE_NAME);
			if ((value != null) && !"".equals(value)) {
				return ConstProp.Operation.PART;
			}
			// 否则发送验证码
			try {
				// 取出已经发送的验证码次数
				String real_cnt = CookiesCRUD.getCookieByName(request,
						ConstProp.BindTel.MAX_CNT_KEY);
				if ((real_cnt == null) || real_cnt.isEmpty()) {
					real_cnt = "0";
				} else {
					if (Integer.parseInt(real_cnt) >= ConstProp.BindTel.MAX_CNT_VALUE) {
						return ConstProp.Operation.OVER;
					}
				}

				// 将次数加上1
				CookiesCRUD.addCookie(response, ConstProp.BindTel.MAX_CNT_KEY,
						(Integer.parseInt(real_cnt) + 1) + "",
						ConstProp.BindTel.MAX_CNT_AGE);

				final String code = userService.sendMsg(tel);
				CookiesCRUD.addCookie(response, ConstProp.BindTel.COOKIE_NAME,
						Digest.md5(code, ConstProp.BindTel.APP_KEY),
						ConstProp.BindTel.MAX_AGE);
				return ConstProp.Operation.SUCCESS;

			}
			catch (final Exception e) {
				return ConstProp.Operation.FAILURE;
			}
		}
	}

	/**
	 * 手机验证码校验
	 * 
	 * @param code
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/telVerify", method = RequestMethod.POST)
	@ResponseBody
	public String telVerify(final String code, final String tel,
			final HttpServletRequest request) {
		final String userCode = Digest.md5(code, ConstProp.BindTel.APP_KEY);
		final String realCode = CookiesCRUD.getCookieByName(request,
				ConstProp.BindTel.COOKIE_NAME);
		if (!userCode.isEmpty() && realCode.equals(userCode)) {
			// 匹配的话更新用户电话
			userService.bindTel(tel);
			return ConstProp.Operation.SUCCESS;
		} else {
			return ConstProp.Operation.FAILURE;
		}
	}

	@RequestMapping(value = "/bindAlipay", method = RequestMethod.POST)
	@ResponseBody
	public String bindAlipay(final String alipay) {
		// 该支付宝账户已经和其它用户绑定
		if (userService.countByAlipay(alipay) > 0) {
			return ConstProp.Operation.EXIST;
		}
		return ConstProp.Operation.SUCCESS;
	}

	/**
	 * 支付宝绑定
	 * 
	 * @param alipay
	 * @return
	 */
	@RequestMapping(value = "/alipayVerify", method = RequestMethod.POST)
	@ResponseBody
	public String alipayVerify(final String alipay) {
		try {
			userService.bindAlipay(alipay);
		}
		catch (final Exception e) {
			e.printStackTrace();
			return ConstProp.Operation.FAILURE;
		}
		return ConstProp.Operation.SUCCESS;
	}

	/**
	 * 
	 * @param step
	 *            1、显示填写用户名界面 <br/>
	 *            2、根据用户名提示邮箱，用户输入邮箱<br/>
	 *            3、判断用户输入邮箱是否正确，正确，则发送邮件<br/>
	 *            4、输入新密码<br/>
	 * @param username
	 * @param email
	 * @param t
	 * @param sign
	 * @param new_pwd
	 * @return
	 */
	@RequestMapping("forget_pwd")
	public String forgetPwd(String step, final String username, String email,
			final String t, final String sign, final String new_pwd,
			final Model model) {
		if ("1".equals(step)) {
		} else if ("2".equals(step)) {
			final User user = userService.findByUserName(username);
			email = user.getEmail();
			if (StringUtil.isEmptyOrNull(email)) {
				step = "0";// 0 表示出错了
			} else {
				// 把testemail@126.com 改成 t*l@126.com
				final String[] arr = email.split("@");
				arr[0] = arr[0].charAt(0) + "*"
						+ arr[0].charAt(arr[0].length() - 1);
				email = arr[0] + "@" + arr[1];
				model.addAttribute("email", email);
				model.addAttribute("username", user.getUsername());
			}
		} else if ("3".equals(step) || (step == null)) {
			final User user = userService.findByEmail(email);
			if (user.getUsername().equals(username)) {
				mailService.updatePwdEmail(email);
				model.addAttribute("email", email);
			} else {
				step = "0";
			}
		} else if ("4".equals(step)) {
			model.addAttribute("email", email);
			model.addAttribute("t", t);
			model.addAttribute("sign", sign);
		} else if ("5".equals(step)) {
			if (Digest.sha1(email + t, null).equals(sign)) {
				final User user = userService.findByEmail(email);
				user.setPassword(Digest.md5(new_pwd));
				userService.update(user);
				model.addAttribute("msg", "密码已更改， 请使用新密码重新登录");
			} else {
				step = "0";
			}
		}
		model.addAttribute("step", step);
		return "user/forget_pwd";
	}

	@Autowired
	public void setUserService(final UserService userService) {
		this.userService = userService;
	}

	@Autowired
	public void setMailService(final MailService mailService) {
		this.mailService = mailService;
	}

}
